package com.example.function.integration.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * @Description：Http请求工具类
 * @Author：fengcheng
 * @Date：2024/10/9 11:36
 */

public class HttpClientUtils {

    private static final Logger logger = getLogger(HttpClientUtils.class);

    private static RequestConfig requestConfig = null;

    static {
        // 设置请求和传输超时时间，单位ms。connetionTimeout：tcp三次握手时间；socketTimeout：客户端从服务器读取数据的timeout
        requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
    }

    /**
     * post请求传输json参数
     *
     * @param url       url地址
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) throws IOException {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), StandardCharsets.UTF_8.name());
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                // 读取服务器返回过来的json字符串数据
                str = EntityUtils.toString(result.getEntity(), StandardCharsets.UTF_8.name());
                // 把json字符串转换成json对象
                jsonResult = JSON.parseObject(str);
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
            httpClient.close();
        }
        return jsonResult;
    }

    /**
     * post请求传输String参数 例如：name=Jack&sex=1&type=2
     * Content-type:application/x-www-form-urlencoded
     *
     * @param url      url地址
     * @param strParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, String strParam) throws IOException {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            if (null != strParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(strParam, StandardCharsets.UTF_8.name());
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                // 读取服务器返回过来的json字符串数据
                str = EntityUtils.toString(result.getEntity(), StandardCharsets.UTF_8.name());
                // 把json字符串转换成json对象
                jsonResult = JSON.parseObject(str);
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
            httpClient.close();
        }
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject httpGet(String url) throws IOException {
        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());
                // 把json字符串转换成json对象
                jsonResult = JSON.parseObject(strResult);
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
            client.close();
        }
        return jsonResult;
    }

    /**
     * post 请求 ，失败直接抛异常
     *
     * @param url
     * @param reqStr
     * @return
     * @throws Exception
     */
    public static String doPost(String url, String reqStr) throws Exception {
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("Url must not be empty");
        }
        if (null == reqStr || reqStr.length() == 0) {
            throw new IllegalArgumentException("Request params must not be empty");
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String postResult;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            StringEntity entity = new StringEntity(reqStr, ContentType.create(ContentType.APPLICATION_JSON.getMimeType(),
                    StandardCharsets.UTF_8.name()));
            httpPost.setEntity(entity);

            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                postResult = EntityUtils.toString(result.getEntity(), StandardCharsets.UTF_8.name());
                return postResult;
            } else {
                logger.error("http调用失败，返回状态非200|url:{} 请求入参:{} 返回结果:{}", url, reqStr, JSON.toJSONString(result));
                throw new RuntimeException("http调用失败，返回状态非200：" + result.getStatusLine().getStatusCode());
            }
        } finally {
            httpPost.releaseConnection();
            httpClient.close();
        }
    }

    /**
     * 带header设置的doPost方法
     *
     * @param url
     * @param reqStr
     * @param header
     * @return
     * @throws Exception
     */
    public static String doPostWithHeader(String url, String reqStr, Map<String, String> header) throws Exception {
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("Url must not be empty");
        }
        if (null == reqStr || reqStr.length() == 0) {
            throw new IllegalArgumentException("Request params must not be empty");
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String postResult;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            StringEntity entity = new StringEntity(reqStr, ContentType.create(ContentType.APPLICATION_JSON.getMimeType(),
                    StandardCharsets.UTF_8.name()));
            httpPost.setEntity(entity);
            for (Map.Entry<String, String> entry : header.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                postResult = EntityUtils.toString(result.getEntity(), StandardCharsets.UTF_8.name());
                return postResult;
            } else {
                logger.error("http调用失败，返回状态非200|url:{} 请求入参:{} header:{} 返回结果:{}", url, reqStr, header, JSON.toJSONString(result));
                throw new RuntimeException("http调用失败，返回状态非200：" + result.getStatusLine().getStatusCode());
            }
        } finally {
            httpPost.releaseConnection();
            httpClient.close();
        }
    }
}
